const express = require('express')
const app = express()
const sqlQuery = require('./sql')

const axios = require('axios')
const { router: socketApi, sockApiInit } = require('./api/api_socket')

const cors = require('cors')
const bodyParser = require('body-parser')

// 配置 cors 跨域
app.use(
  cors({
    methods: ['GET', 'POST'],
    alloweHeaders: [
      'Content-Type',
      'application/json;charset=utf-8;application/x-www-form-urlencoded',
    ],
  })
)
// 配置 post body 解析
app.use(bodyParser.json())
app.use(express.urlencoded({ extended: true }))

// 静态资源目录
app.use('/public/', express.static('./public/'))

// 跨域配置
// app.all('*', function (req, res, next) {
//   console.log(req.method)
//   res.header('Access-Control-Allow-Origin', '*')
//   res.header('Access-Control-Allow-Headers', 'Content-type')
//   res.header(
//     'Access-Control-Allow-Methods',
//     'PUT,POST,GET,DELETE,OPTIONS,PATCH'
//   )
//   res.header('Access-Control-Max-Age', 1728000) //预请求缓存20天
//   next()
// })

/**
 * mysql服务器
 */
app.get('/', (req, res) => {
  // res.send('这是答题服务器')
  res.send('./index.html')
})

// socket 聊天
app.use('/api/socket', socketApi)
sockApiInit(app)

app.get('/api/rtimu', async (req, res) => {
  // 随机获得10个题目
  console.log(req.query)

  let page = req.query.page ? req.query.page : 0

  const strSql = `select * from quizzesinseret limit ${page * 10},10`
  const result = await sqlQuery(strSql)

  res.json(result)
})

// 获取音乐列表，项目 test-music-echo 使用
app.get('/api/getmusiclist', async function (req, res) {
  const { data } = await axios.get(
    'http://www.app-echo.com/api/recommend/sound-day?page=1'
  )

  console.log(data.list)
  const tempListData = []

  data.list.forEach((item, index) => {
    let tempMusicUrl = item.sound.source.split('?')[0]

    tempListData.push({
      name: item.sound.name,
      musicUrl: tempMusicUrl,
      picUrl: item.sound.pic,
    })
  })

  res.json(tempListData)
})

app.listen(3001, () => {
  console.log('Server Start...')
  console.log('http://localhost:3001/')
  console.log('socket:3002')
})
